package com.pixiv.controller;


import com.pixiv.Entity.User;
import com.pixiv.service.UserService;
import com.pixiv.tools.*;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.UUID;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("getUserIcon")
    public void getUserIcon(HttpServletRequest req, HttpServletResponse resp){
        HttpSession hs = req.getSession();
        User u = (User) hs.getAttribute("GLOBAL_USER_OBJECT");

        String road = userService.getUserIconByUserID(u.getUserID() );
        if (u != null) {
            u.outPutPictureStream(resp,road,"/user/init","main.jpg");
        }

    }

    @ResponseBody
    @RequestMapping("updateSex")
    public void Service_modifyUserPhase1(HttpServletRequest req, HttpServletResponse resp)
    {
        HttpSession hs = req.getSession();
        User u = (User) hs.getAttribute("GLOBAL_USER_OBJECT");
        if (u != null)
        {
            String sex = req.getParameter("sex");
            userService.updateSexByUserID(sex,u.getUserID());
            userService.flshUserData(u);
            SendPack.flag(resp,1);
        }else
        {
            SendPack.flag(resp,2);
        }
    }

    @ResponseBody
    @RequestMapping("updateInfor")
    public void Service_modifyUserPhase2(HttpServletRequest req, HttpServletResponse resp)
    {
        resp.setContentType("application/json;charset=utf-8");
        HttpSession hs = req.getSession();
        User u = (User) hs.getAttribute("GLOBAL_USER_OBJECT");
        if (u != null)
        {
            String name = req.getParameter("name");
            String sex = req.getParameter("sex");
            String email = req.getParameter("email");
            String qq = req.getParameter("qq");
            String phone = req.getParameter("phone");
            userService.updatePhaseInforByUserID(name,sex,email,qq,phone,u.getUserID() );
            userService.flshUserData(u);
            SendPrintWriterPacket.sendFlag(resp,1);
        }else
        {
            SendPrintWriterPacket.sendFlag(resp,2);
            NotFoundUser.notGetUser();
        }
    }


    /**
     * 保存用户的临时头像图片
     * @param req
     * @param resp
     */
    @ResponseBody
    @RequestMapping("saveTempIcon")
    public void saveTempIcon(HttpServletRequest req, HttpServletResponse resp)
    {
        HttpSession hs = req.getSession();
        User u = (User) hs.getAttribute("GLOBAL_USER_OBJECT");
        String fileName = (String) hs.getAttribute("updateUserIconTempPath");

        String nameType = fileName.substring(fileName.lastIndexOf(".")).toUpperCase();
        if (".BMP".equals(nameType) || ".JPG".equals(nameType) || ".JPEG".equals(nameType) || ".PNG".equals(nameType))
        {
            String imagePath = "user/user_" + u.getUserID() + "/icon/" + fileName + "_test";
            userService.updateUserIconPathByUserID(u.getUserID(), imagePath);

            FileUtilTool.deleteTempNoName(ProgramStaticGlobal.getPRealPath() + "/user/user_" + u.getUserID() + "/icon", fileName);

            String path = ProgramStaticGlobal.getPRealPath() + "/user/user_" + u.getUserID() + "/icon" + "/" + fileName;
            try {
                InputStream is = new FileInputStream(new File(path));
                OutputStream os = new FileOutputStream(new File(path + "_test"));
                FileUtilTool.resizeImage(is,os,200,"png");
            } catch (Exception e) {
                e.printStackTrace();
            }

            SendPack.flag(resp, 1);
        }else
        {
            SendPack.flag(resp,2);
        }
    }


    /**
     * 上传图片后会执行的函数
     * @param file
     * @param req
     */
    @ResponseBody
    @RequestMapping("updateIcon")
    public String Service_UpdateUserIcon(@RequestParam("file") MultipartFile file, HttpServletRequest req)
    {
        HttpSession hs = req.getSession();
        User u = (User) hs.getAttribute("GLOBAL_USER_OBJECT");
        if(!file.isEmpty())
        {
            String fileName = file.getOriginalFilename();
            //截取文件的后缀 生成新的文件名 避免文件名字重复
            String nameType = fileName.substring(fileName.lastIndexOf(".")).toUpperCase();
            if (".BMP".equals(nameType) || ".JPG".equals(nameType) || ".JPEG".equals(nameType) || ".PNG".equals(nameType))
            {
                String uuid = UUID.randomUUID().toString().replace("-", "");
                String uuidName = uuid + nameType;
                try {
                    String path = ProgramStaticGlobal.getPRealPath() + "/user/user_" + u.getUserID() + "/icon";
                    file.transferTo(new File(path,uuidName));
                    hs.setAttribute("updateUserIconTempPath",uuidName);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return SendPack.getFlag(0);
            }else
            {
                return SendPack.getFlag(1);
            }
        }
        return SendPack.getFlag(2);
    }

    /**
     * 临时的修改图像显示会指向所选的图片
     * @param req
     * @param resp
     */
    @RequestMapping("getTempUserIcon")
    public void Service_getTempUserIcon(HttpServletRequest req, HttpServletResponse resp)
    {
        HttpSession hs = req.getSession();
        User u = (User) hs.getAttribute("GLOBAL_USER_OBJECT");
        if (u != null)
        {
            String tempName = (String) hs.getAttribute("updateUserIconTempPath");
            File file = new File( ProgramStaticGlobal.getPRealPath() + "/user/user_" + u.getUserID() + "/icon", tempName);
            try {
                FileInputStream fis = new FileInputStream(file);
                resp.setContentType("application/octet-stream; charset=utf-8");
                ServletOutputStream outputStream = resp.getOutputStream();
                IOUtils.copy(fis, outputStream);

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }


    }


    @RequestMapping("updateUserFromTemp")
    public void Service_TempIconToFormalIcon(HttpServletRequest req, HttpServletResponse resp)
    {
        resp.setContentType("application/json;charset=utf-8");
        HttpSession hs = req.getSession();
        User u = (User) hs.getAttribute("GLOBAL_USER_OBJECT");
        String fileName = (String) hs.getAttribute("updateUserIconTempPath");

        String nameType = fileName.substring(fileName.lastIndexOf(".")).toUpperCase();
        if (".BMP".equals(nameType) || ".JPG".equals(nameType) || ".JPEG".equals(nameType) || ".PNG".equals(nameType))
        {
            String imagePath = "user/user_" + u.getUserID() + "/icon/" + fileName + "_test";
            userService.updateUserIconPathByUserID(u.getUserID(), imagePath);
            //UserInformationDAO.updateUserIconPathByUserID(u.getUserID(), imagePath);
            FileUtilTool.deleteTempNoName(ProgramStaticGlobal.getPRealPath() + "/user/user_" + u.getUserID() + "/icon", fileName);

            String path = ProgramStaticGlobal.getPRealPath() + "/user/user_" + u.getUserID() + "/icon" + "/" + fileName;
            try {
                InputStream is = new FileInputStream(new File(path));
                OutputStream os = new FileOutputStream(new File(path + "_test"));
                FileUtilTool.resizeImage(is,os,200,"png");
            } catch (Exception e) {
                e.printStackTrace();
            }

            SendPack.flag(resp, 1);
        }else
        {
            SendPack.flag(resp,2);
        }

    }

    @RequestMapping("getUserIconByID")
    public void getUserIconByID(int id, HttpServletResponse resp)
    {
        String road = userService.getUserIconByUserID(id );
        User.outPutPictureStream(resp,road,"/user/init","main.jpg");
    }


}
